import { getUuid } from "@/utils/common.methods";
import Dexie, { Table } from "dexie";

export interface AudioInfo {
  id: string;
  msgId: string;
  file: ArrayBuffer;
  created: number;
}

/** 语音文件暂不上传oss，本地缓存即可 */
export class AudioDB extends Dexie {
  private static _detabase = "hope-audio";
  private _version = 1;
  _table!: Table<AudioInfo>;

  private static _ins: AudioDB = new AudioDB();
  public static get ins(): AudioDB {
    return this._ins ? this._ins : (this._ins = new AudioDB());
  }

  constructor() {
    super(AudioDB._detabase);
    this.version(this._version).stores({
      _table: "id, session, msgId, file, created",
    });
  }
  /** 写入音频文件 */
  async insert(file: ArrayBuffer, msgId: string) {
    const id = getUuid();
    const info = { id, file, msgId, created: Date.now() };
    return await this._table.add(info);
  }

  /** 获取音频使用 msgId */
  async getAudioByMsg(id: string): Promise<ArrayBuffer> {
    const item = await this._table.where("msgId").equals(id).first();
    return item?.file;
  }

  /** 删除 根据msgid */
  async remove(id: string) {
    return await this._table.where("msgId").equals(id).delete();
  }

  /** 批量删除 根据 msgIds */
  async removes(msgIds: string[]) {
    const deletePromises = msgIds.map((msgId) => {
      return this._table.where("msgId").equals(msgId).delete();
    });
    await Promise.all(deletePromises);
  }

  /** 删除该会话关联的所有记录 */
  async clearByQuote(id: string) {
    return await this._table.where("session")?.equals(id)?.delete();
  }

  async clear() {
    return await this._table.clear();
  }
}

export const audioDB = AudioDB.ins;
